<template>
  <div class="echarts_box">
    <div class="echarts_box" ref="echarts_box" :style="{ opacity: data.length == 0 ? '0' : '1' }"></div>
    <!---------------------- 无数据时显示 ---------------------->
    <Nodata class="Nodata" v-show="data.length == 0"></Nodata>
  </div>
</template>

<script>
  import fontSize from "@/utils/fontSize";
  // const elementResizeDetectorMaker = require("element-resize-detector");
  export default {
    mounted() { },
    computed: {
      // ...mapGetters(["echartsColor"]),
    },
    watch: {
      data: {
        // 对对象进行深度监听
        handler(nv) {
          this.drawLine();
        },
        immediate: true,
        deep: true,
      },
      color: "drawLine", // 数值变化是更新图表
      yName: "drawLine", // 数值变化是更新图表
      markLine: "drawLine", // 数值变化是更新图表
      gridRight: "drawLine", // 数值变化是更新图表
      gridLeft: "drawLine", // 数值变化是更新图表
      gridTop: "drawLine", // 数值变化是更新图表
      gridBottom: "drawLine", // 数值变化是更新图表
      nameTextStyle: "drawLine", // 数值变化是更新图表
      barWidth: "drawLine", // 数值变化是更新图表
      xLength: "drawLine", // 数值变化是更新图表
      unit: "drawLine", // 数值变化是更新图表
      xrotate: "drawLine", // 数值变化是更新图表
    },
    props: {
      unit: {
        type: String,
        default: "",
      },
      color: {
        type: String,
        default: "#2478F2",
      },
      markLine: {
        // 标记线
        type: String,
        default: "", //average平均值 custom自定义
      },
      markLineColor: {
        // 标记线
        type: String,
        default: "",
      },
      barWidth: {
        type: [String, Number],
        default: 26,
      },
      yName: {
        // y轴标题
        type: String,
        default: "",
      },
      gridRight: {
        type: String,
        default: "3%",
      },
      gridTop: {
        type: String,
        default: "20%",
      },
      xLength: {
        type: [String, Number],
        default: "18%",
      },
      gridBottom: {
        type: String,
        default: "16%",
      },
      nameTextStyle: {
        type: Array | Object,
        default: function () {
          return [0, 40, 0, 0];
        },
      },
      //x周倾斜
      xrotate: {
        type: [String, Number],
        default: 0,
      },
      gridLeft: {
        type: String,
        default: "8%",
      },
      data: {
        // 返回的数据
        type: Array,
        default: function () {
          return [{
            value: 520,
            name: "温度",
          },
          {
            value: 345,
            name: "湿度",
          },
          {
            value: 234,
            name: "UPS",
          },
          {
            value: 123,
            name: "门禁",
          },
          {
            value: 100,
            name: "消防",
          },];
        },
      },
    },
    mounted() {
      this.drawLine();
    },
    methods: {
      drawLine() {
        try {
          var cw = document.body.clientWidth;
          this.$nextTick(() => {
            let myChart = this.$echarts.init(this.$refs.echarts_box);

            let xData = [];
            let yData = [];
            let allNum = 0;
            for (let item of this.data) {
              xData.push(item.name);
              yData.push(item.value);
              allNum += item.value;
            }
            let markLine = [];
            if (this.markLine == "average") {
              markLine.push({
                type: "average",
                name: "平均值",
                opacity: 0,
                //设置标记点的样式
                itemStyle: {
                  normal: { borderType: "dotted", color: "#08F8B1" },
                },
              });
            }
            if (this.markLine == "custom") {
              markLine.push({
                name: "警戒值",
                yAxis: (allNum / (yData.length * 0.7)).toFixed(0),
                opacity: 0,
                //设置标记点的样式
                itemStyle: {
                  normal: { borderType: "dotted", color: "#FF4618" },
                },
              });
            }
            let option = {
              tooltip: {
                trigger: "axis",
                axisPointer: {
                  type: "line", // 默认为直线，可选为：'line' | 'shadow'
                },
                backgroundColor: "rgba(0,74,174,0.9)", //设置背景颜色
                textStyle: {
                  color: "rgba(255,255,255,1)", //设置文字颜色
                  // fontFamily: "PingFang SC",
                  fontSize: fontSize.fontSize(22),
                },
                formatter: "{b} : {c}" + this.unit,
              },
              grid: {
                top: this.gridTop,
                right: this.gridRight,
                left: this.gridLeft,
                bottom: this.gridBottom,
              },
              xAxis: {
                type: "category",
                data: xData,
                axisLine: {
                  lineStyle: {
                    color: "rgba(207,238,252,0.2)",
                  },
                },
                axisTick: {
                  //y轴刻度线

                  show: false,
                },
                splitLine: { show: false },
                axisLabel: {
                  // margin: 10,
                  color: "rgba(255,255,255,1)",
                  rotate : this.xrotate ,
                  textStyle: {
                    fontSize: fontSize.fontSize(18),
                    // fontFamily: "PingFang SC",
                  },
                  formatter: (name) => {
                    let str = "";
                    if (this.xLength != "") {
                      str =
                        name.length > Number(this.xLength)
                          ? name.slice(0, Number(this.xLength)) + "..."
                          : name;
                    } else {
                      str = name;
                    }
                    return str;
                  },
                },
              },
              yAxis: [
                {
                  // nameGap: '20',
                  splitNumber: 3,
                  nameTextStyle: {
                    color: "rgba(255,255,255,1)",
                    // fontWeight: 400,
                    fontSize: fontSize.fontSize(18),
                    padding: this.nameTextStyle,
                    // fontFamily: "PingFang SC",
                  },
                  name: this.yName,
                  axisLabel: {
                    fontSize: fontSize.fontSize(18),
                    color: "rgba(255,255,255,1)",
                    // fontFamily: "PingFang SC-Bold",
                  },
                  axisLine: {
                    show: false,
                    lineStyle: {
                      color: "rgba(207,238,252,0.2)",
                    },
                  },
                  axisTick: {
                    //y轴刻度线

                    show: false,
                  },
                  splitLine: {
                    lineStyle: {
                      color: "rgba(126,159,182,0.12)",
                    },
                  },
                },
              ],
              series: [
                {
                  type: "bar",
                  data: yData,
                  barWidth: fontSize.fontSize(this.barWidth),
                  itemStyle: {
                    // color: "rgba(9,193,253,1)",
                    normal: {
                      color: new this.$echarts.graphic.LinearGradient(
                        0,
                        1,
                        0,
                        0,
                        [
                          {
                            // 四个数字分别对应 数组中颜色的开始位置，分别为 右，下，左，上。例如（1,0,0,0 ）代表从右边开始渐
                            // 变。offset取值为0~1，0代表开始时的颜色，1代表结束时的颜色，柱子表现为这两种颜色的渐变。
                            offset: 0,
                            color: this.color,
                          },
                          {
                            offset: 1,
                            color: this.color,
                          },
                        ]
                      ),
                    },
                  },

                  markLine: {
                    //设置标记线
                    symbol: "none",
                    data: markLine,
                    lineStyle: {
                      opacity: this.markLine != "" ? 1 : 0,
                      type: "solid",
                    },
                    label: {
                      show: this.markLine != "",
                      position: "end",
                      padding: [-12, 0, 0, -20],
                      // formatter: '{c}'
                      fontSize: 12,
                      formatter: (params) => {
                        return parseInt(params.value);
                      },
                    },
                  },
                },
              ],
            };

            myChart.setOption(option);
            /* 大小自适应 */
            window.addEventListener("resize", () => {
              // h = this.$refs.echarts_box.offsetHeight;
              // console.log(h);
              myChart.resize();
            });
            myChart.resize();
          });
        } catch (e) {
          console.log(e);
          // 错误处理代码片段
        }
      },
    },
  };
</script>

<style lang="scss" scoped>
  .echarts_box {
    width: 100%;
    height: 100%;
    position: relative;

    .Nodata {
      position: absolute;
      top: 0;
      z-index: 10;
    }
  }
</style>